package com.objectdraw.client.objectdraw;
import java.awt.*;
import java.awt.event.*;

/**
 * controls mouse events for drawing lines
 * @author jgulik, cfruehan
 *
 */
public class LineTool implements Tool {

	protected DrawingCanvas canvas;
	protected Point startingMousePosition;
	protected Color saveColor;

	/**
	 * instantiates the tool
	 * @param canvas the canvas upon which the tool acts
	 */
	public LineTool(DrawingCanvas canvas) {
		this.canvas = canvas;
	}

	/**
	 * draw a line between the 2 supplied points
	 * @param p1 
	 * @param p2
	 */
	protected void drawLineSegment(Point p1, Point p2) {
		canvas.getImageBufferGraphics().drawLine(p1.x,p1.y,p2.x, p2.y);
		canvas.repaint();
	}

	/**
	 * start a new line object at point supplied in event e
	 */
	public void mousePressed(MouseEvent e)  {
		/* Establish starting point for next drawing */
		Graphics iBGraphics = canvas.getImageBufferGraphics();
		startingMousePosition = e.getPoint();
		saveColor = canvas.penColor;
		
		iBGraphics.setColor(Color.lightGray);
		drawLineSegment(startingMousePosition, startingMousePosition);
	}

	/**
	 * draw a temporary line between the initial point and the current mouse location
	 */
	public void mouseDragged(MouseEvent e)  {
		Graphics iBGraphics = canvas.getImageBufferGraphics();

		iBGraphics.setColor(Color.lightGray);

		/* draw updated temporary line */
		Point newMousePosition = e.getPoint();
		drawLineSegment(startingMousePosition,newMousePosition);
	}

	/**
	 * draw a line using the initial point and the release point.  push the line object 
	 * onto the object list
	 */
	public void mouseReleased(MouseEvent e) {
		Graphics iBGraphics = canvas.getImageBufferGraphics();
		iBGraphics.setColor(saveColor);
		drawLineSegment(startingMousePosition, e.getPoint());

		LineObject myline=new LineObject(startingMousePosition,e.getPoint(),canvas.getImageBufferGraphics().getColor());
		IDrawingObjectLink myLineLink=new IDrawingObjectLink(myline);
		canvas.push(myLineLink);
	}
}
